var map = null;
var myOptions = {
	zoom: view_level,
	mapTypeControl: true,
	mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
	navigationControl: true,
	mapTypeId: google.maps.MapTypeId.ROADMAP,
	center: new google.maps.LatLng('31.225394428808688','121.47675279999999')
}

function init_map() {
	map = new google.maps.Map(document.getElementById(map_id), myOptions);
	if(p1 == "" && p2 == "" && navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(showPosition);
	}else if(p1 != '' && p2 != '') {
		var c = new google.maps.LatLng(p1, p2);
		map.setCenter(c, view_level);
	}
	markmap();
}

function showPosition(position){
	p1=position.coords.latitude;
	p2=position.coords.longitude;
	var c = new google.maps.LatLng(p1, p2);
	map.setCenter(c, view_level);
}

function markmap() {
    var Center = map.getCenter();
    var lat = new String(Center.lat());
    var lng = new String(Center.lng());
    setLatLng(lat, lng);
	var marker = new google.maps.Marker({
		position: new google.maps.LatLng(lat,lng),
		map: map,
		draggable: true
	});
	google.maps.event.addListener(marker, 'dragstart', function() {
		try {
			map.closeInfoWindow();
		}
		catch (err){
		}
	});
	google.maps.event.addListener(marker, 'dragend', function() {
		var latlng = marker.getPosition();
		lng = String(latlng.lng());
        lat = String(latlng.lat());
        setLatLng(lat,lng);
	});
}

function setLatLng(lat,lng) {
    document.getElementById('point1').value = lat;
    document.getElementById('point2').value = lng;
}

function doSearch(){
	var address = document.getElementById('address').value;
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': address}, function (results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var bounds = results[0].geometry.viewport;
			map.fitBounds(bounds);
			marker.setPosition(results[0].geometry.location);
			marker.setTitle(address);
		} else alert('error');
	});
}

document.onkeydown = function (evt){
	evt = evt || event;
	if (evt.keyCode == 13) {
		doSearch();
	}
};

window.onload = function () {
	init_map();
}